package com.panfeng.xcloud.scheduler.service.impl;

import com.panfeng.xcloud.common.core.configuration.DataDictionaryConfig;
import com.panfeng.xcloud.common.core.enums.CoinTypeEnum;
import com.panfeng.xcloud.common.core.enums.DataDictionaryTypeEnum;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.enums.UserBotStatusTypeEnum;
import com.panfeng.xcloud.common.core.exceptions.BaseBizException;
import com.panfeng.xcloud.common.core.utils.KeyContactUtil;
import com.panfeng.xcloud.common.core.utils.StringUtils;
import com.panfeng.xcloud.common.core.web.vo.InnerTransferVO;
import com.panfeng.xcloud.dao.assets.entity.UserBot;
import com.panfeng.xcloud.scheduler.dao.mapper.UserBotMapperExt;
import com.panfeng.xcloud.scheduler.service.IFeignService;
import com.panfeng.xcloud.scheduler.service.IProfitShiftingService;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ProfitShiftingServiceImpl implements IProfitShiftingService {

    private static Logger log = LoggerFactory.getLogger(ProfitShiftingServiceImpl.class);

    @Autowired
    private IFeignService feignService;

    @Autowired
    private UserBotMapperExt userBotMapperExt;

    @Autowired
    private DataDictionaryConfig dataDictionaryConfig;

    @Override
    public void profitShifting() {
        //获取全部机器人
        List<UserBot> userBots = userBotMapperExt.selectBots(Integer.valueOf(UserBotStatusTypeEnum.ACTIVE.getCode()), null);

        List<String> contractCodes = new ArrayList<>();

        //遍历全部机器人
        for (UserBot userBot : userBots) {
            try {
                String contractCode = KeyContactUtil.getContractCode(userBot.getExchangeType(), userBot.getDestinationCoin(), userBot.getSourceCoin());

                if (contractCodes.contains(contractCode)) {
                    continue;
                } else {
                    contractCodes.add(contractCode);
                }

                //查询可用余额
                BigDecimal avaliableMoney = feignService.getAvaliableMoney(userBot.getExchangeType(), userBot.getUserId(), contractCode);

                //查询利润转移阈值
                BigDecimal profitShifting = new BigDecimal(dataDictionaryConfig.getCodeToNameMap().get(DataDictionaryTypeEnum.profit_shifting.getCode()));

                //可用余额大于利润转移阈值时，进行一次利润转移
                if (avaliableMoney.compareTo(profitShifting) > 0) {
                    BigDecimal needShifting = avaliableMoney.subtract(profitShifting);

                    InnerTransferVO innerTransferVO = new InnerTransferVO();
                    innerTransferVO.setExchangeType(userBot.getExchangeType());
                    innerTransferVO.setUserId(userBot.getUserId());
                    innerTransferVO.setAsset(CoinTypeEnum.USDT.getCode());
                    innerTransferVO.setFrom("linear-swap");
                    innerTransferVO.setTo("spot");
                    innerTransferVO.setMarginAccount(contractCode);
                    innerTransferVO.setAmount(needShifting.setScale(8, BigDecimal.ROUND_DOWN));

                    //转移利润
                    String orderId = feignService.transferInner(innerTransferVO);

                    if (StringUtils.isEmpty(orderId) || orderId.equals("null")) {
                        throw new BaseBizException(ResponseStatusEnum.PROFIT_SHIFTING_FAIL);
                    }

                    //发送消息提醒转移利润成功
                    feignService.sendEmail("用户id:" + userBot.getUserId()
                            + "  交易对:" + contractCode
                            + "  成功转移利润:" + needShifting
                            + "  划转订单号:" + orderId);

                    //睡一下防止超频访问
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                feignService.sendEmail("转移利润定时任务异常，交易对:" + userBot.getDestinationCoin() + userBot.getSourceCoin()
                        + "   用户id:" + userBot.getUserId()
                        + "   异常信息:" + StringUtils.printStackTraceToString(e));
            }
        }
    }

}
